<template>
  <div>
    <title-panel />
    <van-form
      input-align="right"
      error-message-align="right"
      :show-error-message="false"
      show-error
      scroll-to-error
      validate-first
      @failed="onFailed"
      @submit="onSubmit"
    >
      <van-field
        readonly
        :value="obj.recordDate"
        name="recordDate"
        label="记录日期"
        placeholder="请选择时间"
        input-align="right"
        required
        @click="showPicker1 = true"
        :rules="[{ required: true, message: '请选择记录日期' }]"
      />
      <van-popup v-if="!isDisabled" v-model="showPicker1" position="bottom">
        <van-datetime-picker
          v-model="currentDate"
          type="date"
          @confirm="onConfirmStartDate"
          @cancel="showPicker1 = false"
        />
      </van-popup>

      <van-field
        readonly
        name="dieOrHandleType"
        label="处理或死亡原因"
        :value="obj.dieOrHandleType"
        is-link
        required
        placeholder="请选择"
        input-align="right"
        :rules="[{ required: true, message: '请选择处理或死亡原因' }]"
        @click="natureShows = true"
        label-width="110px"
      />
      <van-popup v-if="!isDisabled" v-model="natureShows" position="bottom">
        <van-picker
          show-toolbar
          :columns="unitS"
          value-key="landParcelName"
          @confirm="onConfirmType"
          @cancel="natureShows = false"
        />
      </van-popup>
      <van-field
        readonly
        name="handleMethodCode"
        label="处理方法"
        :value="obj.handleMethodCode"
        is-link
        required
        placeholder="请选择"
        input-align="right"
        :rules="[{ required: true, message: '请选择处理方法' }]"
        @click="natureShows2 = true"
      />
      <van-popup v-if="!isDisabled" v-model="natureShows2" position="bottom">
        <van-picker
          show-toolbar
          :columns="unitS2"
          value-key="landParcelName"
          @confirm="onConfirmType2"
          @cancel="natureShows2 = false"
        />
      </van-popup>
      <van-cell class="btnfrom" :border="false">
        <van-field
          class="fromInput"
          :border="false"
          readonly
          clickable
          name="handleCount"
          label="处理数量 (只)"
          :value="obj.handleCount"
          required
          is-link
          label-width="40%"
          placeholder="请选择"
          input-align="right"
          :rules="[{ required: true, message: '请选择处理数量' }]"
          @click="chooseEarLabel"
        />
        <van-button native-type="button" plain color="#37B5B5" class="addbtn" @click="scanClick()" type="primary"
          >扫一扫</van-button
        >
      </van-cell>
      <div class="spacing" />
      <div class="add-btn">
        <van-button
          block
          type="info"
          color="#37B5B5"
          style="width: 85%; margin: auto; margin-top: 50px"
          native-type="submit"
          size="large"
          :loading="loading"
          loading-text="提交中..."
          >保存</van-button
        >
      </div>
    </van-form>
  </div>
</template>
<script>
import {
  Form,
  Field,
  Calendar,
  RadioGroup,
  Radio,
  Dialog,
  Toast,
  DatetimePicker,
  Picker,
  Button,
  Icon,
  Popup,
  Cell
} from 'vant'
import UploadImg from '@/components/uploadImg'
import TitlePanel from '@/components/titlePanel'
import dayjs from 'dayjs'
import { getValue, setValue, clearValue } from '@/utils/auth'
import { getHandle, postHandle } from '../../api'
export default {
  components: {
    UploadImg,
    TitlePanel,
    [Form.name]: Form,
    [Field.name]: Field,
    [Calendar.name]: Calendar,
    [RadioGroup.name]: RadioGroup,
    [Radio.name]: Radio,
    [Picker.name]: Picker,
    [DatetimePicker.name]: DatetimePicker,
    [Button.name]: Button,
    [Icon.name]: Icon,
    [Popup.name]: Popup,
    [Toast.name]: Toast,
    [Cell.name]: Cell,
    [Dialog.Component.name]: Dialog.Component
  },
  data() {
    return {
      unitS: [],
      unitS_Code: [],
      unitS2: [],
      unitS2_Code: [],
      showPicker2: false,
      contentList: '',
      fileInfoList: [],
      currentDate: new Date(),
      showPicker1: false,
      loading: false,
      flag: true,
      //   typeList: [],
      //   resultList: [],
      isDisabled: false,
      natureShows: false,
      natureShows2: false,
      natureNameList: [],
      siteList: [],
      natureShow: false,
      natureNameLists: [],
      fertiliList: [],
      obj: {
        recordDate: dayjs(new Date()).format('YYYY-MM-DD'),
        dieOrHandleType: this.addHuiXian('dieOrHandleType'),
        handleMethodCode: this.addHuiXian('handleMethodCode'),
        handleCount: getValue('earTag2') ? JSON.parse(getValue('earTag2')).length : '',
        individualInfoIds: getValue('earTag2') ? JSON.parse(getValue('earTag2')) : []
      },
      contentObj: {},
      type: null
    }
  },
  created() {
    this.getUnitList()
    this.getUnitList2()


  },
  mounted() {
    this.$bridge.register('backScanData', data => {
      if (JSON.parse(data).individualId) {
        const arr = [JSON.parse(data).individualId]
        setValue('earTag2', JSON.stringify(arr))
        this.obj.handleCount = 1
        this.obj.individualInfoIds = arr
      } else {
        Toast('羊只信息未录入')
      }
    })
    this.$bridge.register('refresh', data => {
      if (getValue('addDead-obj')) {
        this.obj.recordDate = this.addHuiXian('recordDate')
        this.obj.dieOrHandleType = this.addHuiXian('dieOrHandleType')
        this.obj.handleMethodCode = this.addHuiXian('handleMethodCode')
        this.obj.handleCount = getValue('earTag2') ? JSON.parse(getValue('earTag2')).length : ''
        this.obj.individualInfoIds = getValue('earTag2') ? JSON.parse(getValue('earTag2')) : []
      }
    })
  },
  methods: {
    scanClick() {
      this.$bridge.call('base.scanOneScan')
    },

    // 选择耳标之后,回显已经填写过的数据项
    addHuiXian(param) {
      return getValue('addDead-obj') ? JSON.parse(getValue('addDead-obj'))[param] : ''
    },
    // 新增跳转选择耳标
    chooseEarLabel() {
      // 跳转耳标选择之前缓存已经填写好的数据
      // 选择完耳标之后回显已经填写好的数据
      setValue('addDead-obj', JSON.stringify({ ...this.obj }))
      this.$bridge.call('addWmCheckEarTag2')
    },
    // 请求处理原因列表数据
    getUnitList() {
      this.unitS = []
      getHandle('/agri/api/common/businessData/queryList', { pCode: 'T000010_DIE_OR_HANDLE_TYPE' }).then(res => {
        console.log(res)
        res.data.rows.forEach(item => {
          this.unitS.push(item.name)
          this.unitS_Code.push(item.code)
        })
      })
    },
    // 请求处理方法列表数据
    getUnitList2() {
      this.unitS = []
      getHandle('/agri/api/common/businessData/queryList', { pCode: 'T000010_DIE_HANDLE_METHOD' }).then(res => {
        console.log(res)
        res.data.rows.forEach(item => {
          this.unitS2.push(item.name)
          this.unitS2_Code.push(item.code)
        })
      })
    },
    // 获取默认数据
    initialize(id) {},
    // 时间
    onConfirmStartDate(value) {
      this.obj.recordDate = dayjs(value).format('YYYY-MM-DD')
      this.showPicker1 = false
    },
    // 疫苗接种数量这里是多选写的时候改下逻辑
    onConfirmTypes(value) {
      const index = this.fertiliList.indexOf(value)
      if (index == -1) {
        this.fertiliList.push(value)
      } else {
        this.fertiliList.splice(index, 1)
      }
      this.obj.FertilizersPesticides = this.fertiliList.map(item => item.label).join(',')
      this.natureShow = false
    },
    // 方式和原因
    onConfirmType(value) {
      this.obj.dieOrHandleType = value
      this.natureShows = false
    },
    onConfirmType2(value) {
      this.obj.handleMethodCode = value
      this.natureShows2 = false
    },
    onFailed(errorInfo) {
      Toast(errorInfo.errors[0].message)
    },
    onSubmit(value) {
      this.loading = true
      // let imgInfos = this.obj.imgInfos.map((item) => item.url).join(",");
      // 发送保存网络请求
      this.onSave()
    },
    onSave() {
      const params = {
        recordDate: this.obj.recordDate,
        dieOrHandleType: this.unitS_Code[this.unitS.indexOf(this.obj.dieOrHandleType)],
        handleMethodCode: this.unitS2_Code[this.unitS2.indexOf(this.obj.handleMethodCode)],
        handleCount: this.obj.handleCount || 111111,
        individualInfoIds: this.obj.individualInfoIds || ['a', 'b', 'c'],
        houseInfoId: '',
        subjectInfoId: getValue('subjectInfoId'),
        tenantCode: getValue('tenantCode'),
        callChannel: getValue('callChannel'),
        loginUserId: getValue('loginUserId')
      }
      postHandle('/agri/api/yzbzh/dieHarmlesshandle/save', params).then(res => {
        console.log(res)
        // 新增成功跳转列表页
        if (res.status == 0) {
          Toast.success('操作成功')
          // 删除保存的耳标信息
          clearValue('earTag2')
          // 清除缓存的回显信息
          clearValue('addDead-obj')
          this.$bridge.call('base.closePage')
        } else {
          this.loading = false
          Toast.fail(res.msg || '操作失败')
        }
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.tip {
  padding-top: 15px;
  color: #999999;
  font-size: 12px;
  line-height: 16px;
  margin: auto;
}
.btn {
  width: 80%;
  margin: 50px auto 0 auto;
}
.btn > div {
  height: 50px;
  background: #2871fe;
  border-radius: 4px;
  text-align: center;
  line-height: 50px;
  color: #ffffff;
  font-size: 17px;
}
.btn .cancel {
  margin-top: 20px;
  background: rgba(40, 113, 254, 0.1);
  border: 1px solid #2871fe;
  color: #2871fe;
}
::v-deep .van-field__label {
  width: 6em;
}
.bthStyle {
  width: 56px;
  height: 20px;
  border-radius: 10px;
  border: 1px solid #2871fe;
}
.active {
  background-color: #fff;
  color: #2871fe;
}
.add-btn {
  padding-bottom: 20px;
}
.addbtn {
  width: 50px;
  height: 24px;
  font-size: 13px;
  padding: 0;
  margin-right: 13px;
  z-index: 10;
  float: right;
  margin-top: -38px;
}
.btnfrom {
  padding: 1px 0;
}
.fromInput {
  width: 86%;
}
</style>
